﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using yq.IService;
using Db;

namespace yq.Service
{
    public class File : IFile
    {
        /// <summary>
        /// 查询文件
        /// </summary>
        /// <param name="seek"></param>
        /// <returns></returns>
        public IList<Model.Logic.FileList> SelectFile(Search.File.FileListSeek search)
        {
            var dal = new yq.Business.FileListDal();

            if (string.IsNullOrEmpty(search.Ttile) == false)
            {
                dal.WherePlus(obj => obj.Ttile.Like(search.Ttile));
            }

            if (search.Status != Enums.FileList.Status.Default)
            {
                dal.WherePlus(obj => obj.Status == search.Status);
            }

            if (search.IsPrivate != Enums.BooleanType.UnKnow)
            {
                dal.WherePlus(obj => obj.IsPrivate == search.IsPrivate);
            }

            if (string.IsNullOrEmpty(search.SuperiorId) == false)
            {
                dal.WherePlus(obj => obj.SuperiorId == search.SuperiorId);
            }

            if (string.IsNullOrEmpty(search.UserId) == false)
            {
                dal.WherePlus(obj => obj.UserId == search.UserId);
            }

            if (search.Type != Enums.FileList.Type.Default)
            {
                dal.WherePlus(obj => obj.Type == search.Type);
            }

            return dal.GetList(new DbHelper());
        }

        /// <summary>
        /// 查询历史版本
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public IList<Model.Logic.FileVer> SelectFileVer(string fileId)
        {
            var dal = new yq.Business.FileVerDal();
            dal.WherePlus(obj => obj.FileId == fileId);
            return dal.GetList(new DbHelper(), obj => obj.CheckInTime, true);
        }

        /// <summary>
        /// 查询权限
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public IList<Model.Logic.FilePurview> SelectFilePurview(string fileInfoId)
        {
            var dal = new yq.Business.FilePurviewDal();
            dal.WherePlus(obj => obj.FileId == fileInfoId);

            return dal.GetList(new DbHelper());
        }

        /// <summary>
        /// 用户的权限
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public yq.Enums.FliePurview.PurviewLevel SelectPurviewToUser(string fileInfoId,string userId)
        {
            var cnhelp= new DbHelper();

            var dal = new yq.Business.FilePurviewDal();
            dal.WherePlus(obj => obj.FileId == fileInfoId);
            //文件的权限列表
            var list = dal.GetList(cnhelp);
       
            string departmentId= new yq.Business.UserInfoDal().GetModel(obj => obj.UserId == userId, cnhelp).DepartmentId;
            var  teamlist = new yq.Business.TeamUserDal().GetList(obj => obj.UserId == userId, cnhelp);
        
            var pwTemplist= list.Where(obj => obj.FliePwId ==fileInfoId + "_" + userId);
            var pwDepartmentlist = list.Where(obj => obj.FliePwId == fileInfoId + "_" + departmentId);
            pwTemplist = pwTemplist.Union(pwDepartmentlist);
            foreach (var team in teamlist)
            {
                var temp = list.Where(obj => obj.FliePwId == fileInfoId + "_" + team.TeamId);
                pwTemplist = pwTemplist.Union(temp);
            }
            pwTemplist=pwTemplist.OrderByDescending(obj => obj.PurviewLevel.GetHashCode());

            return pwTemplist.Count() == 0 ? Enums.FliePurview.PurviewLevel.Default: pwTemplist.ToList()[0].PurviewLevel;
        }


        /// <summary>
        /// 添加文件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Dictionary.ReturnValue<string> AddFile(Model.Logic.FileList model, string fileId)
        {
            Func<DbHelper, yq.CaCheRefresh, Dictionary.ReturnValue<string>> dbfun = (cn, ca) =>
            {
                Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
                model.SubmitTime = DateTime.Now;
                model.Status = Enums.FileList.Status.Normal;
                model.Type =  Enums.FileList.Type.File;
                model.FileinfoId = "".ExtNewGuid();
                model.IsCheckOut = Enums.BooleanType.No;
                model.IsHide = Enums.BooleanType.No;
                model.CheckUserId = "";
                model.Path = GetPath(model.SuperiorId);

                //并创建第一个ver 版本信息
                yq.Model.Logic.FileVer ver = new Model.Logic.FileVer()
                {
                    CheckInTime = DateTime.Now,
                    IsCurrent = Enums.BooleanType.Yes,
                    FileId = fileId,
                    FileInfoId = model.FileinfoId
                };
                model.VerId = new yq.Business.FileVerDal().Add(ver, cn);
                new yq.Business.FileListDal().Add(model, model.FileinfoId, cn);
                cn.Commit();
                rv.True(model.FileinfoId);

                return rv;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }

        /// <summary>
        /// 添加文件夹
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Dictionary.ReturnValue<string> AddFolder(Model.Logic.FileList model)
        {
            Func<DbHelper, yq.CaCheRefresh, Dictionary.ReturnValue<string>> dbfun = (cn, ca) =>
            {
                Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
                model.IsHide = Enums.BooleanType.No;
                model.IsCheckOut =  Enums.BooleanType.No;
                model.SubmitTime = DateTime.Now;
                model.Status = Enums.FileList.Status.Normal;
                model.Type = Enums.FileList.Type.Folder;
                model.VerId = "";
                model.Path = GetPath(model.SuperiorId);
                model.FileinfoId = new yq.Business.FileListDal().Add(model, cn);
                cn.Commit();
                rv.True(model.FileinfoId);

                return rv;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }

        /// <summary>
        /// 重新上传新的版本
        /// </summary>
        /// <param name="model"></param>
        /// <param name="ver"></param>
        /// <returns></returns>
        public Dictionary.ReturnValue<string> EditFileVer(string  fileinfoId, Model.Logic.FileVer ver)
        {
            Func<DbHelper, yq.CaCheRefresh, Dictionary.ReturnValue<string>> dbfun = (cn, ca) =>
            {
                Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
                var dal = new yq.Business.FileListDal();
                var dalver = new yq.Business.FileVerDal();


                //修改文件信息的当前版本
                var info = dal.GetModel(obj => obj.FileinfoId == fileinfoId, cn);

                if (info.IsCheckOut== Enums.BooleanType.No || info.CheckUserId == ver.CheckInUserId)
                {
                    info.VerId = "".ExtNewGuid();
                    dal.Update(info, cn);

                    //修改旧的当前版本
                    var oldVer = dalver.GetModel(obj => obj.IsCurrent == Enums.BooleanType.Yes && obj.FileInfoId == fileinfoId, cn);
                    oldVer.IsCurrent = Enums.BooleanType.No;
                    dalver.Update(oldVer, cn);

                    //创建新版本
                    ver.CheckInTime = DateTime.Now;
                    ver.FileInfoId = fileinfoId;
                    ver.IsCurrent = Enums.BooleanType.Yes;
                    ver.VerId = info.VerId;
                    dalver.Add(ver, cn);

                    cn.Commit();
                    rv.True(ver.VerId);
                }
                else
                {
                    rv.False("文件已被签出");
                }

                return rv;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }

        /// <summary>
        /// 只编辑文件
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public Dictionary.ReturnValue<string> EditFile(Model.Logic.FileList model)
        {
            Func<DbHelper, yq.CaCheRefresh, Dictionary.ReturnValue<string>> dbfun = (cn, ca) =>
            {
                Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
                var dal = new yq.Business.FileListDal();
                model.Path = GetPath(model.SuperiorId);
                if (dal.Update(model, cn) != 0)
                {
                    cn.Commit();
                    rv.True(model.FileinfoId);
                }
                else
                {
                    rv.False("");
                }

                return rv;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }

  
        /// <summary>
        /// 删除到回收站
        /// </summary>
        /// <param name="fileId"></param>
        /// <returns></returns>
        public Dictionary.ReturnValue<string> RecoverFlie(string fileId)
        {
            Func<DbHelper, yq.CaCheRefresh, Dictionary.ReturnValue<string>> dbfun = (cn, ca) =>
            {
                Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
                var dal = new yq.Business.FileListDal();
                var info = dal.GetModel(obj => obj.FileinfoId == fileId, cn);
                info.Status = Enums.FileList.Status.Del;
                if (dal.Update(info, cn) != 0)
                {
                    cn.Commit();
                    rv.True(info.FileinfoId);
                }
                else
                {
                    rv.False("");
                }

                return rv;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }

        /// <summary>
        /// 彻底删除
        /// </summary>
        /// <param name="fileinfoId"></param>
        /// <returns></returns>
        public Dictionary.ReturnValue<string> DelFlie(string fileinfoId)
        {
            Func<DbHelper, yq.CaCheRefresh, Dictionary.ReturnValue<string>> dbfun = (cn, ca) =>
            {
                Dictionary.ReturnValue<string> rv = new Dictionary.ReturnValue<string>();
                var dal = new yq.Business.FileListDal();
                int count = dal.GetCount(obj => obj.SuperiorId == fileinfoId, cn);
                if (count == 0)
                {
                    if (dal.Delete(fileinfoId, cn))
                    {
                        cn.Commit();
                        rv.True(fileinfoId);
                    }
                    else
                    {
                        rv.False("删除失败");
                    }
                }
                else
                {
                    rv.False("本文件夹下有其他文件不能删除");
                }

                return rv;
            };

            return Db.DBTrans.DoTrans(dbfun);
        }


        /// <summary>
        /// 文件路径
        /// </summary>
        /// <param name="superiorId"></param>
        /// <returns></returns>
        private string GetPath(string superiorId) 
        {
            string path = "/";
            if (superiorId != "-1")
            {
                path = yq.Model.Logic.FileList.Load(superiorId).Path;
                path = path + superiorId + "/";
            }

            return path;
        }


        
    }
}
